package com.xxg.renrensearch.service;

import com.xxg.renrensearch.cache.ResourceCache;
import com.xxg.renrensearch.dao.Product;
import com.xxg.renrensearch.dao.RenrenShopGoodsCategory;
import com.xxg.renrensearch.dao.RenrenShopGoodsCategoryDao;
import com.xxg.renrensearch.domain.result.BaseResult;
import com.xxg.renrensearch.domain.result.CategoryResult;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 资源接口实现
 *
 * @author xuxiaogang
 * @date 2021-11-24
 */
@Service
public class ResourceServiceImpl implements ResourceService {
    private final ResourceCache resourceCache;
    private final RenrenShopGoodsCategoryDao renrenShopGoodsCategoryDao;

    public ResourceServiceImpl(ResourceCache resourceCache, RenrenShopGoodsCategoryDao renrenShopGoodsCategoryDao) {
        this.resourceCache = resourceCache;
        this.renrenShopGoodsCategoryDao = renrenShopGoodsCategoryDao;
    }

    @Override
    public BaseResult<Object> getCity() {
        return new BaseResult<>(resourceCache.getCityCache());
    }

    @Override
    public BaseResult<List<CategoryResult>> getCategoryByShopId(Integer shopId) {
        List<RenrenShopGoodsCategory> categories = renrenShopGoodsCategoryDao.selectByShopId(shopId);
        Map<Integer, CategoryResult> map = new HashMap<>(categories.size() * 4 / 3 + 1);
        List<CategoryResult> results = new LinkedList<>();
        for (RenrenShopGoodsCategory e : categories) {
            CategoryResult categoryResult = new CategoryResult();
            categoryResult.setOrder(e.getDisplayOrder());
            categoryResult.setCategory(e);
            categoryResult.setChildren(new LinkedList<>());
            map.put(e.getId(), categoryResult);
            // 查询父节点
            if (e.getParentId() != 0) {
                CategoryResult parent = map.get(e.getParentId());
                // 父分类不存在时则表示父分类已被删除
                if (parent != null) {
                    parent.getChildren().add(categoryResult);
                }
            } else {
                results.add(categoryResult);
            }
        }
        // 父节点排序
        results.sort(Comparator.comparingInt(CategoryResult::getOrder));
        // 二级节点排序
        results.forEach(e -> {
            e.getChildren().sort(Comparator.comparingInt(CategoryResult::getOrder));
            // 三级节点排序
            e.getChildren().forEach(f -> f.getChildren().sort(Comparator.comparingInt(CategoryResult::getOrder)));
        });
        return new BaseResult<>(results);
    }
}
